@page "/tag/{tag}"

@using MyBlogServer.Models
@using MyBlogServer.Services
@inject PostService PostService
@inject IJSRuntime JSRuntime
@inject IMarkdownService MarkdownService

@rendermode InteractiveServer

<PageTitle>标签: @tag</PageTitle>

<div class="blog-container">
    <div class="tags-page">
        <h1>标签: @tag</h1>

        @if (_posts == null || !_posts.Any())
        {
            <div class="alert alert-info">
                <p>该标签下暂无文章</p>
            </div>
        }
        else
        {
            <div class="blog-content-wrapper">
                <div class="blog-posts-container">
                    @foreach (var post in _posts)
                    {
                        <div class="blog-post">
                            <h2><a href="/post/@post.Slug">@post.Title</a></h2>
                            <div class="meta">
                                <span>发布时间: @post.CreatedAt.ToString("yyyy年MM月dd日")</span>
                            </div>
                            @if (!string.IsNullOrEmpty(post.Summary))
                            {
                                <div class="summary">
                                    @post.Summary
                                </div>
                            }
                            else
                            {
                                <div class="summary">
                                    @((MarkupString)MarkdownService.ToHtml(post.Content.Length > 200 ? post.Content.Substring(0, 200) + "..." : post.Content))
                                </div>
                            }
                            <div class="read-more">
                                <a href="/post/@post.Slug">阅读全文</a>
                            </div>
                        </div>
                    }
                </div>
                
                <aside class="tag-cloud-sidebar">
                    <h3>标签云</h3>
                    @foreach (var t in PostService.GetAllTags())
                    {
                        <a href="/tag/@t" class="tag">@t</a>
                    }
                </aside>
            </div>
        }
    </div>
</div>

@code {
    [Parameter] public string? tag { get; set; }
    private IEnumerable<Post> _posts = new List<Post>();

    protected override async Task OnParametersSetAsync()
    {
        if (!string.IsNullOrEmpty(tag))
        {
            _posts = await PostService.GetPostsByTagAsync(tag);
        }
    }
    
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            // 调用JavaScript函数为标签分配随机颜色
            await JSRuntime.InvokeVoidAsync("assignRandomTagColors");
        }
    }
}